package com.gz.mylife.app;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.wheel.adapter.AbstractWheelTextAdapter;
import com.gz.mylife.widget.LoadingCover;
import com.gz.mylife.widget.LoadingCover.OnLoadingCoverRefreshListener;
import com.gz.mylife.widget.wheel.OnWheelChangedListener;
import com.gz.mylife.widget.wheel.OnWheelScrollListener;
import com.gz.mylife.widget.wheel.WheelView;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zl.smartmall.library.IGZAddress;
import com.zl.smartmall.library.listener.GetFloorAddressListener;
import com.zl.smartmall.library.po.AddressGZ;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class SelectFloorActivity extends BaseActivity implements OnClickListener,OnLoadingCoverRefreshListener{
	
	private PullToRefreshListView mListView;
	private LoadingCover mloadCover;
	private TextView mTvAddress;
	private int currentAddress = -1;
	private MenuItem ensureItem;
	private int cmid;
	
	
	private List<AddressGZ> GzProvince;
	private AddressGZ mCurrentProvince;
	private AddressGZ mCurrentCity;
	private AddressGZ mCurrentCountry;
	
	private boolean scrolling = false; 
	
	private MyFloorListener mListener;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_selectfloor);
		cmid = getIntent().getIntExtra("cmid", 0);
		mListener = new MyFloorListener(this);
		GzProvince = new ArrayList<AddressGZ>();
//		mActionBar.setTitle("选择小区楼号");
		setActionbarTitle("选择小区楼号", true);
		
//		test();
		initView();
	}
	
	private void test() {
		for(int i = 0;i<5;i++){
			AddressGZ province = new AddressGZ();
			GzProvince.add(province);
			province.setId(i);
			province.setName("provice_"+i);
			List<AddressGZ> GzCity = new ArrayList<AddressGZ>();
			for(int j = 0;j<3;j++){
				AddressGZ city = new AddressGZ();
				GzCity.add(city);
				int index = i*10+j;
				city.setId(index);
				city.setName("city_"+index);
				List<AddressGZ> GzCountry = new ArrayList<AddressGZ>();
				for(int k = 0;k<6;k++){
					AddressGZ country = new AddressGZ();
					GzCountry.add(country);
					int index2 = i*100+j*10+k;
					country.setId(index2);
					country.setName("中心花园小区"+index2);
				}
				city.setLists(GzCountry);
			}
			province.setLists(GzCity);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.updata_menu, menu);
		ensureItem = menu.findItem(R.id.action_updata);
//	    ensureItem = menu.add(0, 100, 0, "确定");
		MenuItemCompat.setShowAsAction(ensureItem,MenuItemCompat.SHOW_AS_ACTION_ALWAYS|MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		if(mCurrentCountry == null){
//			ensureItem.setVisible(false);
			setActionbarTitle("选择小区楼号", false);
		}
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_updata:
			Intent intent = new Intent();
			intent.putExtra("cmid", mCurrentCountry.getCmid());
			intent.putExtra("id", mCurrentCountry.getId());
			intent.putExtra("phone", mCurrentCountry.getPhone());
			intent.putExtra("name", mCurrentProvince.getName()+"，"+mCurrentCity.getName()+"，"+mCurrentCountry.getName());
			setResult(101, intent);
			finish();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void initView() {
		mloadCover = (LoadingCover) findViewById(R.id.layout_loading_cover);
		mloadCover.setOnLoadingCoverRefreshListener(this);
		mTvAddress = (TextView) findViewById(R.id.selectfloor_tv_address);
		loadData();
	}

	private void initWheel() {
		 final WheelView country = (WheelView) findViewById(R.id.country);
	        country.setVisibleItems(3);
//	        country.setViewAdapter(new CountryAdapter(this));
	        country.setViewAdapter(new MyAdapter(getApplicationContext(), GzProvince));
	        mCurrentProvince = GzProvince.get(0);

	        final WheelView city = (WheelView)findViewById(R.id.city);
	        city.setVisibleItems(3);
	        
	        // 地区选择
	        final WheelView ccity = (WheelView)findViewById(R.id.ccity);
	        ccity.setVisibleItems(3);
	        

	        country.addChangingListener(new OnWheelChangedListener() {
				@Override
				public void onChanged(WheelView wheel, int oldValue, int newValue) {
				    if (!scrolling) {
				    	updateCities(city, country.getCurrentItem());
				    }
				}
			});
	        
	        country.addScrollingListener( new OnWheelScrollListener() {
	            @Override
				public void onScrollingStarted(WheelView wheel) {
	                scrolling = true;
	            }
	            @Override
				public void onScrollingFinished(WheelView wheel) {
	                scrolling = false;
	                updateCities(city, country.getCurrentItem());
	            }
	        });
	        
	      

	        city.addChangingListener(new OnWheelChangedListener() {
				@Override
				public void onChanged(WheelView wheel, int oldValue, int newValue) {
				    if (!scrolling) {
//				        updatecCities(ccity, ccities, country.getCurrentItem(),newValue);
				    	updatecCities(ccity, city.getCurrentItem());
				    }
				}
			});
	        
	        city.addScrollingListener( new OnWheelScrollListener() {
	            @Override
				public void onScrollingStarted(WheelView wheel) {
	                scrolling = true;
	            }
	            @Override
				public void onScrollingFinished(WheelView wheel) {
	                scrolling = false;
	                updatecCities(ccity, city.getCurrentItem());
	            }
	        }); 
	        
	        ccity.addChangingListener(new OnWheelChangedListener() {
				
				@Override
				public void onChanged(WheelView wheel, int oldValue, int newValue) {
					  if (!scrolling) {
						  mCurrentCountry = mCurrentCity.getLists().get(ccity.getCurrentItem());
					  }
					  updataAddress();
				}
			});
	         
	        ccity.addScrollingListener( new OnWheelScrollListener() {
	            @Override
				public void onScrollingStarted(WheelView wheel) {
	                scrolling = true;
	            }
	            @Override
				public void onScrollingFinished(WheelView wheel) {
	                scrolling = false; 
	                mCurrentCountry = mCurrentCity.getLists().get(ccity.getCurrentItem());
	                updataAddress();
	            }
	        }); 
	         
	        country.setCurrentItem(GzProvince.size()/2);
	}
	
	private void updataAddress() {
		String addressStr = mCurrentProvince.getName()+"-"+mCurrentCity.getName()+"-"+mCurrentCountry.getName();
		  mTvAddress.setText(addressStr);
	}
	
	private void updateCities(WheelView city, int index) {
    	mCurrentProvince = GzProvince.get(index);
    	MyAdapter adapter = new MyAdapter(getApplicationContext(), mCurrentProvince.getLists());
    	adapter.setTextSize(12);
    	city.setViewAdapter(adapter);
    	city.setCurrentItem(mCurrentProvince.getLists().size()/2);    
    }
	private void updatecCities(WheelView city, int index) {
    	mCurrentCity = mCurrentProvince.getLists().get(index);
    	MyAdapter adapter = new MyAdapter(getApplicationContext(), mCurrentCity.getLists());
    	adapter.setTextSize(12);
    	city.setViewAdapter(adapter);
    	city.setCurrentItem(mCurrentCity.getLists().size()/2);     
    }

	private void loadData() {
		IGZAddress.getInstance().getFloorAddress(cmid, mListener);
	}


	@Override
	public void onClick(View v) {
		
	}
	

	@Override
	public void onLoadingCoverRefresh() {
		loadData();
	}

	private class MyAdapter extends AbstractWheelTextAdapter {
    	// Countries names
    	private List<AddressGZ> mLists;
    	/**
    	 * Constructor
    	 */
    	protected MyAdapter(Context context,List<AddressGZ> lists) {
    		super(context, R.layout.country_layout, NO_RESOURCE);
    		this.mLists = lists;
    		setItemTextResource(R.id.country_name);
    		
    	}
    	
    	@Override
    	public View getItem(int index, View cachedView, ViewGroup parent) {
    		View view = super.getItem(index, cachedView, parent); 
    		return view;
    	}
    	
    	@Override
    	public int getItemsCount() {
    		return mLists.size();
    	}
    	
    	@Override
    	protected CharSequence getItemText(int index) {
    		return mLists.get(index).getName();
    	}
    }

	
	private static class MyFloorListener extends GetFloorAddressListener{
		private SelectFloorActivity mOuter;
		
		public MyFloorListener(SelectFloorActivity outer){
			this.mOuter = outer;
		}
		
		public void release(){
			new WeakReference<SelectFloorActivity>(mOuter);
		}

		@Override
		public void onResponseSuccess(List<AddressGZ> lists) {
			if(mOuter == null){
				return;
			}
			
			mOuter.GzProvince.addAll(lists);
			mOuter.initWheel();
			mOuter.mloadCover.onRefreshSuccess();
			mOuter.ensureItem.setVisible(true);
		}

		@Override
		public void onNoMoreData() {
			if(mOuter == null){
				return;
			}
			mOuter.mloadCover.onRefreshFailed("没有数据");
		}

		@Override
		public void onNoNetWork() {
			if(mOuter == null){
				return;
			}
			mOuter.mloadCover.onRefreshFailed();
			Toast.makeText(mOuter.getApplicationContext(), Define.MSG_NO_NETWORK, Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onResponseFailed() {
			if(mOuter == null){
				return;
			}
			mOuter.mloadCover.onRefreshFailed();
		}
		
	}

}
